package de.thw.web.tld;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import de.thw.web.object.Form;

public class ModelForm extends SimpleTagSupport {

	protected Form form;

	protected String pathPrefix = "";

	public void setForm(Form form) {
		this.form = form;
	};

	public void setPathPrefix(String prefix) {
		this.pathPrefix = prefix;
	};

	public void doTag() throws JspException, IOException {

		PageContext pageContext = (PageContext) this.getJspContext();
		JspWriter out = pageContext.getOut();

		try {
			if (this.form == null) {
				throw new Exception("Form not set!");
			}

			if (this.form.getPath() != "") {
				String path = this.pathPrefix + this.form.getPath() + ".jsp";
				try {

					pageContext
							.setAttribute("showTitle",
									this.form.getShowTitle(),
									PageContext.REQUEST_SCOPE);
					pageContext.setAttribute("object", this.form.getModel(),
							PageContext.REQUEST_SCOPE);

					pageContext.include(path);

					//this.setJspContext(pageContext);

				} catch (Exception e) {
					throw new Exception("File[" + path + "] not found!");
				}
			} else {
				throw new Exception("Path empty!");
			}

		} catch (Exception e) {
			String text = "Formular konnte nicht geladen werden.";
			text += "(";
			text += e.getMessage();
			text += ")";
			out.println(text);
			System.out.println(text);
		}
	};

};